package com.ca.ui.core.adapter;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ui.core.R;
import com.ca.ui.core.bean.PaperInfo;
import com.ca.ui.core.util.ImageUtils;

import java.util.ArrayList;
import java.util.List;

public class PaperHistoryAdapter extends RecyclerView.Adapter<PaperHistoryAdapter.PaperHistoryHolder> {

    private List<PaperInfo> list;

    public PaperHistoryAdapter(List<PaperInfo> list) {
        this.list = list == null ? new ArrayList<>() : list;
    }

    @NonNull
    @Override
    public PaperHistoryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.paper_history_item_layout, parent, false);
        return new PaperHistoryHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PaperHistoryHolder holder, int position) {

        PaperInfo paperInfo = list.get(position);

        ImageUtils.loadRoundImage(holder.headerImage.getContext(), paperInfo.getHeaderUrl(), holder.headerImage, 10);
        holder.nameView.setText(paperInfo.getName());
        holder.timeView.setText(paperInfo.getTime());
        holder.titleView.setText(paperInfo.getTitle());

        //  点击事件
        holder.parent.setOnClickListener(v -> {});
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void setList(List<PaperInfo> list) {

        if (list == null) {
            list = new ArrayList<>();
        }

        //  按照时间排序
        list.sort((o1, o2) -> o2.getTime().compareTo(o1.getTime()));

        if (!this.list.equals(list)) {
            this.list = list;
            notifyDataSetChanged();
        }
    }

    public static class PaperHistoryHolder extends RecyclerView.ViewHolder {

        public ConstraintLayout parent;
        public ImageView headerImage;
        public TextView nameView;
        public TextView timeView;
        public TextView titleView;

        public PaperHistoryHolder(@NonNull View itemView) {
            super(itemView);

            parent = itemView.findViewById(R.id.cl_parent);
            headerImage = itemView.findViewById(R.id.iv_header);
            nameView = itemView.findViewById(R.id.tv_name);
            timeView = itemView.findViewById(R.id.tv_time);
            titleView = itemView.findViewById(R.id.tv_title);
        }
    }
}
